package com.huiwings.pdf;

import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

public class PDFUtils {

    /**
     * 提取
     *
     * @param file         PDF文件
     * @param targetFolder 图片存放目录
     * @return
     */
    public static boolean extractImages(File file, String targetFolder) {
        boolean result = false;

        try {
            //加载文档
            PDDocument document = PDDocument.load(file);

            Iterator<PDPage> iter = document.getDocumentCatalog().getPages().iterator();

            int pageNum = 0;
            while (iter.hasNext()) {//遍历page
                PDPage page = iter.next();
                pageNum++;
                PDResources resources = page.getResources();
                int count = 0;
                for (COSName cosName : resources.getXObjectNames()) {//遍历单页内对象
                    if (resources.isImageXObject(cosName)) {//图片对象
                        count++;
                        PDImageXObject imageXObject = (PDImageXObject) resources.getXObject(cosName);
                        String name = file.getName() + "_" + pageNum + "_" + count;
                        File outputFile = new File(targetFolder + File.separator + name);
                        //imageXObject.createInputStream();
                        BufferedImage bi = imageXObject.getImage();
                        ImageIO.write(bi, "jpg", outputFile);//
                    }
                }
            }
            result = true;
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return result;
    }

    public static void main(String[] args) {
        File pdfFile = new File("/home/huiwings/Desktop/temp/pdf/demo.pdf");
        String targetFolder = "/home/huiwings/Desktop/temp/pdf/output";
        extractImages(pdfFile, targetFolder);
    }


}
